package math.spbu.ru.historycharts;

import math.spbu.ru.historycharts.charts.AbstractChart;
import math.spbu.ru.historycharts.model.DatePoint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class ChartsView extends View {

	private float xDown = 0;

	private AbstractChart mChart;
	private static IDataProvider provider;

	public ChartsView(Context context, AbstractChart chart,
			IDataProvider dataProvider) {
		super(context);
		mChart = chart;
		provider = dataProvider;
		this.setOnTouchListener(new OnTouchListener());
	}

	protected void onDraw(Canvas canvas) {
		canvas.drawColor(Color.WHITE);
		xDown = this.getWidth();
		int width = this.getWidth(), height = this.getHeight();
		mChart.draw(canvas, 0, 0, width, height);
	}

	public static IDataProvider getDataProvider() {
		return provider;
	}

	public void repaint() {
		invalidate();
	}

	private class OnTouchListener implements View.OnTouchListener {
		float width;
		boolean isMove = false;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Context context = v.getContext();

			if (MotionEvent.ACTION_DOWN == event.getAction()) {
				xDown = event.getX();
				DatePoint datePoint = provider.getDateValueByXY(event.getX(),
						event.getY());
				if (datePoint != null) {
					CharSequence text = datePoint.toString();
					Toast toast = Toast.makeText(context, text,
							Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.TOP | Gravity.LEFT,
							(int) event.getX(), (int) event.getY());
					toast.show();
				}
				isMove = false;
				return true;
			}

			if (MotionEvent.ACTION_MOVE == event.getAction()) {
				isMove = true;
			}

			if (MotionEvent.ACTION_UP == event.getAction()) {
				if (isMove) {
					width = ChartsView.this.getWidth();
					double delta = (xDown - event.getX()) / width;

					provider.getRenderer().updateRange(delta);

					repaint();
					return true;
				}
			}
			return true;
		}
	}
}
